<template>
  <el-dialog
    :title="
      dialogType === 'add' ? '请输入本次参赛人员的批次号' : '编辑参赛人员'
    "
    :model-value="dialogVisible"
    :close-on-click-modal="false"
    class="dialog-loading"
    width="600px"
    @update:model-value="emit('update:dialogVisible', $event)"
  >
    <el-text class="batch-tip" type="warning"
      >注：批次号相同的人员会被认为是同一批参赛人员，系统会根据年级自动区分</el-text
    >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="batch-form"
    >
      <el-form-item label="批次号" label-width="67px" prop="batch">
        <el-input
          v-model="formData.batch"
          placeholder="请输入日期-批次号，如20250506-1"
        />
        <!-- <el-button class="button-search" type="primary" @click="handleAddBatch">添加</el-button>
        <el-button class="button-search" type="primary" plain @click="handleDelBatch(index)">删除</el-button> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('update:dialogVisible', false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  droneApi,
  fireApi,
  gobangApi,
  obstacleApi,
  logisticsApi,
} from '@/api/modules'
import { typeFieldMap } from '@/config/type'
import useAppStore from '@/store/modules/app.js'
import { ElLoading } from 'element-plus'

const appStore = useAppStore()
const activeTab = computed(() => appStore.activeTab)

const emit = defineEmits(['update:dialogVisible', 'end'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  competitionType: {
    type: String,
    default: '',
  },
  groupCategory: {
    type: String,
    default: '',
  },
})
const dialogType = ref('add')
const formRef = ref(null)
const formData = reactive({ batch: '' })
const formRules = reactive({
  batch: [
    { required: true, message: '请输入批次号', trigger: 'blur' },
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入批次号'))
        } else if (!/^\d{8}-\d{1,8}$/.test(value)) {
          callback(new Error('批次号格式错误，正确格式为：YYYYMMDD-NNNNN'))
        } else {
          const dateStr = value.split('-')[0]
          const date = new Date(
            dateStr.slice(0, 4) +
              '-' +
              dateStr.slice(4, 6) +
              '-' +
              dateStr.slice(6, 8)
          )
          if (date.toString() === 'Invalid Date' || date.getFullYear() < 2000) {
            callback(new Error('请输入有效的日期'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur',
    },
  ],
})

const apiMap = {
  gobang: gobangApi,
  drone: droneApi,
  fire: fireApi,
  obstacle: obstacleApi,
  logistics: logisticsApi,
}

const fullScreenLoading = (text) => {
  return ElLoading.service({
    lock: true,
    text: text || '正在加载数据...',
    fullscreen: true,
    target: 'dialog-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

const handleSubmit = async () => {
  const loading = fullScreenLoading()
  try {
    const params = {
      batchNo: formData.batch,
      groupCategory: props.groupCategory,
      playType: typeFieldMap[appStore.activeTab],
    }
    const res = await apiMap[appStore.activeTab].scoreInit.post(params)

    loading.close()

    // 判断响应是否为文件
    if (
      res instanceof Blob ||
      (res.type &&
        res.type.includes(
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )) ||
      (res.type && res.type.includes('application/octet-stream'))
    ) {
      ElMessage.success('比赛已开始，小组赛信息Excel文件下载中！')
      // 是文件，执行下载
      download(res, `${formData.batch}.xlsx`)
      ElMessage.success('文件下载成功！')
    } else if (res?.code === 200 && res.message.includes('成功')) {
      // 是普通JSON响应
      ElMessage.success('比赛开始！')
    } else {
      ElMessage.error(res.message || '系统错误，请稍后重试')
    }

    emit('update:dialogVisible', false)
    emit('end')
  } catch (err) {
    loading.close()
    ElMessage.error(err.message || '系统错误，请稍后重试')
    emit('update:dialogVisible', false)
    emit('end')
    console.log('下载失败', err)
  }
}
// 兼容所有浏览器下载二进制文件
const download = (data, filename) => {
  try {
    if (!data) {
      console.error('下载失败：没有接收到数据')
      return
    }

    // 确保数据是Blob类型，并检查是否为Excel文件
    const blob =
      data instanceof Blob
        ? data
        : new Blob([data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          })

    // 验证文件大小，Excel文件不应该太小
    if (blob.size < 100) {
      // 小于100字节可能不是有效的Excel文件
      console.error('下载失败：文件大小异常，可能不是有效的Excel文件')
      ElMessage.error('下载失败：文件格式异常，请联系管理员')
      return
    }

    // IE浏览器使用msSaveOrOpenBlob API
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, filename)
      return
    }

    // 其他现代浏览器
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', filename)

    // 添加到DOM，触发下载，然后清理
    document.body.appendChild(link)
    link.click()

    // 下载启动后清理
    setTimeout(() => {
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url) // 释放URL对象
    }, 100)
  } catch (error) {
    console.error('文件下载失败:', error)
    ElMessage.error('文件下载失败，请稍后重试')
  }
}
// data是二进制文件，filename是下载文件的命名
</script>

<style scoped lang="scss">
.batch-form {
  :deep .el-form-item__content {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-input {
      flex: 1;
      margin-right: 10px;
    }
  }

  .button-search {
    min-width: 50px;
  }
}

.batch-tip {
  display: block;
  margin-bottom: 15px;
  font-size: 14px;
  color: #f56c6c;
}
</style>
